package com.dic.activity;

import java.util.ArrayList;
import java.util.List;

import com.dic.R;
import com.dic.adapter.Listadapter;
import com.dic.model.Dic;
import com.dic.quickaction.ActionItem;
import com.dic.quickaction.QuickAction;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

public class BookActivity extends Activity implements OnGestureListener {
	private Button deleteall;
	private ListView list;
	private TextView nowords;
	private Listadapter dicAdaptar;
	private Dic curDic;
	private List<Dic> curdiclist;
	private SQLiteDatabase database;
	private final String DATABASE_PATH = "/data/data/com.dic/databases/";
	private final String DATABASE_FILENAME = "english.db3";

	private QuickAction quickAction;
	private ActionItem delete;
	private GestureDetector detector;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.book_view);

		this.getApplicationContext();
		deleteall = (Button) findViewById(R.id.btn_delete_all);
		list = (ListView) findViewById(R.id.lv_book);
		nowords = (TextView) findViewById(R.id.tv_nowords);
		getdata();

		quickAction = new QuickAction(this, QuickAction.HORIZONTAL);
		delete = new ActionItem(1, " 删除 ", null);
		quickAction.addActionItem(delete);
		quickAction.setOnActionItemClickListener(new QuickActionClick());

		deleteall.setOnClickListener(new Deleteallclick());

		list.setOnItemClickListener(new ItemClick());
		list.setOnItemLongClickListener(new ItemlongClick());

		detector = new GestureDetector(this);

	}

	private void getdata() {
		if (database == null || !database.isOpen()) {
			database = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH + DATABASE_FILENAME, null);
		}

		String sql = "select id, words, explain, bookmark from ENGLISH where bookmark=1";
		Cursor cursor = database.rawQuery(sql, null);
		List<Dic> arrView = new ArrayList<Dic>();
		Dic dicitem = null;
		while (cursor.moveToNext()) {
			int index = 0;
			dicitem = new Dic();
			dicitem.setId(cursor.getInt(index++));
			dicitem.setWord(cursor.getString(index++));
			dicitem.setExplain(cursor.getString(index++));
			dicitem.setMark(cursor.getInt(index++));
			arrView.add(dicitem);
		}
		if (!arrView.isEmpty()) {
			nowords.setVisibility(8);
			list.setVisibility(0);
			deleteall.setEnabled(true);
			dicAdaptar = new Listadapter(arrView, BookActivity.this);
			list.setAdapter(dicAdaptar);
			curdiclist = arrView;
			cursor.close();

		} else {
			list.setVisibility(8);
			nowords.setVisibility(0);
			deleteall.setEnabled(false);
		}
	}

	class ItemClick implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			curDic = curdiclist.get(arg2);
			Intent intent = new Intent(BookActivity.this, DicDetailActivity.class);
			intent.putExtra("dic", curDic);
			startActivity(intent);
			database.close();
		}

	}

	class ItemlongClick implements AdapterView.OnItemLongClickListener {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// TODO Auto-generated method stub
			curDic = curdiclist.get(arg2);
			quickAction.show(arg1, -1, -1, true);

			return false;
		}

	}

	class QuickActionClick implements QuickAction.OnActionItemClickListener {
		@Override
		public void onItemClick(QuickAction source, int pos, int actionId) {
			curDic.setMark(0);
			deletebookmark();

			// Toast.makeText(getApplicationContext(), quickAction.getActionItem(actionId-1).getTitle().toString(),Toast.LENGTH_SHORT).show();

		}
	};

	private void deletebookmark() {
		String[] id = { String.valueOf(curDic.getId()) };
		ContentValues cv = new ContentValues();
		cv.put("bookmark", curDic.getMark());
		database.update("ENGLISH", cv, "id=?", id);
		database.close();
		getdata();
	}

	class Deleteallclick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			deleteall.setClickable(false);
			AlertDialog.Builder builder = new AlertDialog.Builder(BookActivity.this);

			builder.setMessage(R.string.suredeleteall).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					ContentValues cv = new ContentValues();
					cv.put("bookmark", 0);
					database.update("ENGLISH", cv, "bookmark=?", new String[] { "1" });
					database.close();
					getdata();
					deleteall.setClickable(true);
				}
			}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					deleteall.setClickable(true);
				}
			});
			builder.show();
		}

	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		detector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getdata();
		deleteall.setClickable(true);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub

		TabHost mTabHost = (((TabActivity) getParent()).getTabHost());
		int tabId = mTabHost.getCurrentTab();

		if (Math.abs(e1.getY() - e2.getY()) > 100) {
			// Toast.makeText(context, "WRONG!!!!", Toast.LENGTH_LONG).show();
			return false;
		}

		if ((e1.getX() - e2.getX()) > 50 && Math.abs(velocityX) > 100) {
			// Toast.makeText(context, "To Right!!!!", Toast.LENGTH_LONG).show();
			if (tabId != 2) {
				tabId++;
			}

		} else if ((e2.getX() - e1.getX()) > 50 && Math.abs(velocityX) > 100) {
			// Toast.makeText(context, "To Left!!!!", Toast.LENGTH_LONG).show();
			if (tabId != 0) {
				tabId--;
			}
		}
		mTabHost.setCurrentTab(tabId);

		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

}
